package cn.study.springsecurityoauth2.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

import java.io.Serializable;

/**
 * 注解类的解析文件,使用注解控制权限管理
 * @ClassName MyPermissionEvaluator
 * @Author swj
 * @Date 2020/9/9 20:33
 */
@Configuration
public class MyPermissionEvaluator implements PermissionEvaluator {
    private Logger logger = LoggerFactory.getLogger(MyPermissionEvaluator.class);
    @Override
    public boolean hasPermission(Authentication authentication, Object o, Object o1) {
        boolean accessable = false;
        logger.info(authentication.getPrincipal().toString());

        if(authentication.getPrincipal().toString().compareToIgnoreCase("anonymousUser") != 0){
            String privilege = o+"-"+o1;
            for (GrantedAuthority authority : authentication.getAuthorities()) {
                if(privilege.equalsIgnoreCase(authority.getAuthority())){
                    accessable = true;
                    break;
                }
            }
        }
        return accessable;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable serializable, String s, Object o) {
        return false;
    }
}
